<?php
class Shopping_Model_Product extends Zend_Db_Table{
	protected $_name 	= 'products';
	protected $_primary = 'id';
	protected $_ids;
	
	
	public function findUsers($id){
		$db = Zend_Registry::get('connectDb');
		$select = $db->select()
		             ->from('users as u',array('u.user_name','u.user_avatar','u.first_name','u.last_name'))
		             ->where('u.id = ?', $id,'INTEGER');
		$result = $db->fetchRow($select);
		return $result;
	}
	
	public function findProduct($id){
		$db = Zend_Registry::get('connectDb');
		$select = $db->select()
					->from('products as p')
					->where('p.id = ?', $id,'INTEGER');
		$result = $db->fetchRow($select);
		return $result;
	}
	public function itemInSelectbox($arrParam =null, $options = null){
		$db = Zend_Registry::get('connectDb');
		if($options == null){
			$select = $db->select()
			->from('product_category AS pc',array('id','name','status','parents','order','created_by'))
			->order('pc.order ASC');
			$result = $db->fetchAll($select);
		}
		if($options['task']=='admin-edit'){
			$select = $db->select()
			->from('product_category AS pc',array('id','name','status','parents','order','created_by'))
			->where('id != ?',$arrParam['id'],'INTEGER')
			->order('pc.order ASC');
			$result = $db->fetchAll($select);
		}
		$system = new Zendvn_System_Recursive($result);
		$result = $system->buildArray(0);
		$tmp = array('id'=>0,'name'=>'Select a item','level'=>1,'order'=>1,'parents'=>0);
		array_unshift($result,$tmp);
		return $result;
	}
	public function getItem($arrParam,$options=NULL){
	//------------------TASK == PUBLIC-DETAIL|| TASK ==ADMIN-INFO------------------------------
		if($options['task'] == 'public-detail'||$options['task'] == 'admin-info'){
			$db = Zend_Registry::get('connectDb');
			$select = $db->select()
						->from('products')
						->where('id = ?', $arrParam['id']);
			$result = $db->fetchRow($select);
			
			
		}		
		return $result;
	}
	public function countItem($arrParam = null,$options = null){
	//------------------TASK == ADMIN-COUNT-ITEM ------------------------------
		if($options['task']=='admin-count-item'){
			$db = Zend_Registry::get('connectDb');
			$ssFilter = $arrParam['ssFilter'];
			$select = $db->select()
						 ->from('products as p',array('COUNT(p.id) AS totalItem'));
			
			if(!empty($ssFilter['keywords'])){
				$keywords = '%' . $ssFilter['keywords'] . '%';
				$select->where('p.name LIKE ?',$keywords,'STRING');
			}

			if(!empty($ssFilter['slbgroup'])){
				//Tim cac category con cua no
				$selectCategory = $db->select()
				->from('product_category');
				$resultCategory = $db->fetchAll($selectCategory);
				$system = new Zendvn_System_Recursive($resultCategory);
				$resultRecusive = $system->buildArray($ssFilter['slbgroup']);
				if(count($resultRecusive)==0){
					$select->where('p.cat_id =  ?',$ssFilter['slbgroup'],'INTEGER');
				}else{
					foreach ($resultRecusive as $keyRecusive=>$valRecusive){
						$select->orWhere('p.cat_id =  ?',$valRecusive['id'],'INTEGER');
					}
				}
			}
			$result = $db->fetchOne($select);
			
		}
	//------------------TASK == PUBLIC-INDEX ------------------------------
		if($options['task']== 'public-index'){
			$db = Zend_Registry::get('connectDb');
			$select = $db->select()
					 	->from('products as p',array('COUNT(p.id) AS totalItem'))
						->where('p.status = 1');
			$result = $db->fetchOne($select);
		}
	//------------------TASK == PUBLIC-CATEGORY ------------------------------
		if($options['task']== 'public-category'){
			$db = Zend_Registry::get('connectDb');
			$select = $db->select()
					->from('products as p',array('COUNT(p.id) AS totalItem'))
					->where('p.status = 1')
					->where('cat_id IN('. $this->_ids .')');
			$result = $db->fetchOne($select);
		}
		
		return $result;
	}
	public function listItem($arrParam =null, $options = null){
	
	//------------------TASK == VIEW-CART------------------------------	
		if($options['task']== 'view-cart'){
			if(count($arrParam['cart'])>0){
				$i = 1;
				foreach ($arrParam['cart'] as $key => $val){
					if($i == 1){
						$ids = $key;
					}else{
						$ids.= ',' .$key;
					}
					$i++;
				}
				$db = Zend_Registry::get('connectDb');
				$select = $db->select()
							->from('products as p',array('id','name','price','selloff','cat_id'))
							->where('p.status = 1') 
							->where('p.id IN('.$ids.')'); 
				$result = $db->fetchAll($select);
			}
		}
	//------------------TASK == PUBLIC-INDEX ------------------------------
		if($options['task']== 'public-index'){
			$paginator = $arrParam['paginator'];
			$db = Zend_Registry::get('connectDb');
			$select = $db->select()
						 ->from('products as p',array('id','name','picture','price','selloff','cat_id'))
						 ->join('product_category as pc','pc.id = p.cat_id',array('name as category_name'))
						 ->where('p.status = 1')
						 ->order('publish_date DESC');
			if($paginator['itemCountPerPage']>0){
				$page = $paginator['currentPage'];
				$rowCount = $paginator['itemCountPerPage'];
				$select->limitPage($page,$rowCount);
			}
			$result = $db->fetchAll($select);
		}
	//------------------TASK == PUBLIC-CATEGORY ------------------------------
		if($options['task'] == 'public-category'){
			$paginator = $arrParam['paginator'];
			$db = Zend_Registry::get('connectDb');
			$select = $db->select()
						 ->from('product_category', array('id','name','parents'))
						 ->where('status = 1');
			$resultCategory = $db->fetchAll($select);		
			$system = new Zendvn_System_Recursive($resultCategory);
			$newArray = $system->buildArray($arrParam['cid']);
			
			$tmp[] = $arrParam['cid'];	
			if(!empty($newArray)){
				foreach ($newArray as $key => $val){
					$tmp[] = $val['id'];
				}	 
			}
			$ids = implode(',',$tmp);
			$this->_ids = $ids;
			$paginator  = $arrParam['paginator'];
			$select = $db->select()
						 ->from('products as p',array('id','name','picture','price','selloff','cat_id'))
						 ->join('product_category as pc','pc.id = p.cat_id',array('name as category_name'))
						 ->where('p.status = 1')
						 ->where('p.cat_id IN (' . $ids . ')')
						 ->order(' id DESC')
						 ->limitPage($paginator['currentPage'],$paginator['itemCountPerPage']);
								 
			$result = $db->fetchAll($select);
		}
	//------------------TASK == ADMIN-LIST ------------------------------------------
		if($options['task']== 'admin-list'){
			$ssFilter = $arrParam['ssFilter'];
			$paginator = $arrParam['paginator'];
			$db = Zend_Registry::get('connectDb');
			//$db = Zend_Db::factory($adapter,$config);
			$select = $db->select()
						->from('products as p',array('id','name','picture','status','order','author','cat_id','special','selloff','price'))
						->join('product_category as pc','pc.id = p.cat_id',array('name as category_name'));
			if($paginator['itemCountPerPage']>0){
				$page = $paginator['currentPage'];
				$rowCount = $paginator['itemCountPerPage'];
				$select->limitPage($page,$rowCount);
			}
			if(!empty($ssFilter['keywords'])){
				$keywords = '%' . $ssFilter['keywords'] . '%';
				$select->where('p.name LIKE ?',$keywords,'STRING');
			}
			
			if(!empty($ssFilter['slbgroup'])){
				//Tim cac category con cua no
				$selectCategory = $db->select()
									 ->from('product_category');
				$resultCategory = $db->fetchAll($selectCategory);
				$system = new Zendvn_System_Recursive($resultCategory);
				$resultRecusive = $system->buildArray($ssFilter['slbgroup']);
				if(count($resultRecusive)==0){
					$select->where('p.cat_id =  ?',$ssFilter['slbgroup'],'INTEGER');
				}else{
					foreach ($resultRecusive as $keyRecusive=>$valRecusive){
						$select->orWhere('p.cat_id =  ?',$valRecusive['id'],'INTEGER');
					}	
				}
			}
			if(!empty($ssFilter['colum']) && !empty($ssFilter['by'])){
				$select->order($ssFilter['colum'].' '. $ssFilter['by']);
			}
			
			$result = $db->fetchAll($select);
		}
		
		
		return $result;
	}
	public function saveItem($arrParam=null,$options=null){		
		if($options['task']== 'admin-add'){
			$row = $this->fetchNew();
			$row['name'] 		= $arrParam['name'];
			if(!empty($arrParam['picture'])){
				$row['picture'] 		= $arrParam['picture'];
			}
			$row['order'] 			= $arrParam['order'];
			$row['status'] 			= $arrParam['status'];
			$row['created'] 		= date("Y-m-d");
			$row['price']           = $arrParam['price'];
			$row['special']         = $arrParam['special'];
			$row['selloff']         = $arrParam['selloff'];
			$row['publisher']       = $arrParam['publisher'];
			$row['publish_date']    = date("Y-m-d",strtotime($arrParam['year'] . '-' . $arrParam['month'] . '-' . $arrParam['day']));;
			$row['author']          = $arrParam['author'];
			$row['content']         = $arrParam['content'];
			$row['weight']          = $arrParam['weight'];
			$row['size']            = $arrParam['size'];
			$row['page']            = $arrParam['page'];
			$row['translators']     = $arrParam['translators'];
			$row['cat_id']          = $arrParam['cat_id'];
			$row['created']         = date('Y-m-d H:m:s');
			$info =  new Zendvn_System_Info();
			$created_by = $info->getMemberInfo('id');
			$row['created_by'] 	= $created_by;
			$row->save();
		}
		if($options['task']== 'admin-edit'){
			
			$where = 'id = '. $arrParam['id'];
			$row = $this->fetchRow($where);
			
			$row->name 				= $arrParam['name'];
			if(!empty($arrParam['picture'])){
				$row->picture 		= $arrParam['picture'];
			}
			$row->order 			= $arrParam['order'];
			$row->status 			= $arrParam['status'];
			$row->created			= date("Y-m-d");
			$row->price             = $arrParam['price'];
			$row->special           = $arrParam['special'];
			$row->selloff           = $arrParam['selloff'];
			$row->publisher         = $arrParam['publisher'];
			$row->publish_date      = date("Y-m-d",strtotime($arrParam['year'] . '-' . $arrParam['month'] . '-' . $arrParam['day']));;
			$row->author            = $arrParam['author'];
			$row->content           = $arrParam['content'];
			$row->weight            = $arrParam['weight'];
			$row->size              = $arrParam['size'];
			$row->page              = $arrParam['page'];
			$row->translators       = $arrParam['translators'];
			$row->cat_id            = $arrParam['cat_id'];
			
			$info =  new Zendvn_System_Info();
			$modified_by = $info->getMemberInfo('id');
			$row->modified_by 		= $modified_by;		
				
			$row->modified 			= date("Y-m_d H:m:s");
			
			$row->save();
		}
	}

	public function deleteItem($arrParam=null,$options=null){
		
		if($options['task']== 'admin-delete'){
				$product = $this->findProduct($arrParam['id']);
				if(!empty($product['picture'])){
					$upload = new Zendvn_File_Upload();
					$upload->removeFile(FILES_PATH . '/product/orignal/' . $product['picture']);
					$upload->removeFile(FILES_PATH . '/product/img200x300/' . $product['picture']);
					$upload->removeFile(FILES_PATH . '/product/img57x84/' . $product['picture']);
					$upload->removeFile(FILES_PATH . '/product/img82x122/' . $product['picture']);
					
				}
				$where = 'id = '. $arrParam['id'];
				$this->delete($where); 
		}
	
		if($options['task']== 'admin-multidelete'){
			$cid = $arrParam['cid'];
			foreach ($cid as $keyId => $valueId){
				$product = $this->findProduct($valueId);
				if(!empty($product['picture'])){
					$upload = new Zendvn_File_Upload();
					$upload->removeFile(FILES_PATH . '/product/orignal/' . $product['picture']);
					$upload->removeFile(FILES_PATH . '/product/img200x300/' . $product['picture']);
					$upload->removeFile(FILES_PATH . '/product/img57x84/' . $product['picture']);
					$upload->removeFile(FILES_PATH . '/product/img82x122/' . $product['picture']);
						
				}
				$where = 'id = '. $valueId;
				$this->delete($where);
			}
		}
	}
	public function changeStatus($arrParam=null,$options=nul){
		if($options['task']== 'admin-status'){	
			$cid = $arrParam['cid'];
			if(count($cid)>0){
				if($arrParam['type']==1){
					$status =1 ;
				}else{
					$status =0 ;
				}
				$ids = implode(',',$cid);
				$data = array('status'=>$status);
				$where = 'id IN ('.$ids.')';
				$this->update($data,$where);	
			}
			if($arrParam['id']>0){
				if($arrParam['type'] ==1){
					$status =1 ;
				}else{
					$status =0 ;
				}
				$data = array('status'=>$status);
				$where = 'id ='. $arrParam['id'];
				$this->update($data,$where);
			}
		}
		
	
	}
	public function sortItem($arrParam =null, $options = null){
		$cid 	= $arrParam['cid'];
		$order  = $arrParam['order'];
		if(count($cid)>0){
			foreach ($cid as $key=>$value){
				$data  = array('order'=>$order[$value]);
				$where = 'id = '. $value;
				$this->update($data,$where);
			}
		}
	}
}